var base = getApp();

// 加
Number.prototype.add = function (arg) {
  var r1, r2, m;
  try { r1 = this.toString().split(".")[1].length; } catch (e) { r1 = 0; }
  try { r2 = arg.toString().split(".")[1].length; } catch (e) { r2 = 0; }
  m = Math.pow(10, Math.max(r1, r2));
  return (this * m + arg * m) / m;
}
// 减
Number.prototype.subduct = function (arg) {
  var r1, r2, m, n;
  try { r1 = this.toString().split(".")[1].length; } catch (e) { r1 = 0; }
  try { r2 = arg.toString().split(".")[1].length; } catch (e) { r2 = 0; }
  m = Math.pow(10, Math.max(r1, r2));
  // n=(r1>=r2)?r1:r2; // 控制精度
  // return ((arg1*m-arg*m)/m).toFixed(n);
  return (this * m - arg * m) / m;
}
// 乘
Number.prototype.mul = function (arg) {
  var m = 0, s1 = this.toString(), s2 = arg.toString();
  try { m += s1.split(".")[1].length; } catch (e) { }
  try { m += s2.split(".")[1].length; } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
} 
// 除
Number.prototype.div = function (arg) {
  var t1, t2, r1, r2;
  try { t1 = this.toString().split(".")[1].length; } catch (e) { t1 = 0; }
  try { t2 = arg.toString().split(".")[1].length; } catch (e) { t2 = 0; }
  r1 = Number(this.toString().replace(".", ""));
  r2 = Number(arg.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}

Page({
  data: {
    cartList: [],
    info: {},
    selectAll: 0,
    url: base.path.url
  },

  onShow: function (e) {
    var that = this;
    base.user.user_id = wx.getStorageSync('user_id');
    wx.setStorageSync('cart_info', '')
    wx.request({
      url: base.path.api + 'ShopCart.GetUserCart',
      data:{
        md5key: base.user.session_key,
        uid: base.user.user_id,
        aid: base.user.aid
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
        console.log(result)
        base.sessionId(base);
        var carList=[];
        if (result.ret == 200) {
          if(result.data.length>0){
            for (var i = 0; i < result.data.length; i++) {
              var id = parseInt(result.data[i].id);
              var aid = parseInt(result.data[i].aid);
              var uid = parseInt(result.data[i].uid);
              var skuid = parseInt(result.data[i].skuid);
              var goods_id = parseInt(result.data[i].goods_id);
              var goods_num = parseInt(result.data[i].goods_num);
              var sell_money = parseFloat(result.data[i].sell_money);
              var name = result.data[i].name;
              var val_name = result.data[i].val_name;
              var image_url = result.data[i].image_url;
              var supplierid = result.data[i].supplierid;
              var checked = 0;
              if (i == 0) {
                checked = 1;
              }
              carList.push({ "id": id, "aid": aid, "uid": uid, "skuid": skuid, "goods_id": goods_id, "supplierid": supplierid, "goods_num": goods_num, "sell_money": base.returnFloat(sell_money), "name": name, "val_name": val_name, "image_url": image_url, "checked": checked });
              // console.log(id)
            }
            that.setData({
              cartList: carList,
              info: { num: parseInt(result.data[0].goods_num), total: base.returnFloat(Number(parseFloat(result.data[0].sell_money)).mul(parseInt(result.data[0].goods_num))) }
            });
          }else{
            that.setData({
              cartList: carList,
              info: { num: 0, total: 0 }
            });
          }
          
        }
      }
    })
  },

  onShareAppMessage: function () {
    return {
      title: base.user.shareTitle,
      desc: base.user.shareDesc,
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 更改数量
   */
  changeNum: function (e) {
    var that = this;
    var numtype = parseInt(e.currentTarget.dataset.type);
    var num = numtype + parseInt(e.currentTarget.dataset.num);
    var id = parseInt(e.currentTarget.dataset.id);
    var that = this;
    base.user.user_id = wx.getStorageSync('user_id');
    // return;
   
    var _num = that.data.info.num;
    var total = that.data.info.total;
    var data = that.data.cartList;
    var obj = [];
    for (var k in data) {
      if (data[k].id == id) {
        if (num <= 0) {
          return false;
        }else{
          data[k].goods_num = num;
          if (data[k].checked == 1) {
            _num += numtype;
            total = parseInt(Number(total).add(Number(data[k].sell_money).mul(numtype)) * 100) / 100;
            console.log(data[k].goods_num + "," + data[k].sell_money + "," + data[k].sell_money * numtype + "," + total)
          }
        }
        
      }

      obj.push(data[k]);
    }
    that.setData({
      cartList: obj,
      info: { num: _num, total: total }
    });


    
    wx.request({
      url: base.path.api + 'ShopCart.UpdateCart',
      data: {
        cartid: id,
        quantity: num,
        md5key: base.user.session_key,
        uid: base.user.user_id,
        aid: base.user.aid,
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
        if (result.ret == 200) {
          
        } else if (result.status == -9) {
          base.login();
        }
      }
    })
  },

  /**
   * 勾选
   */
  onSelect: function (e) {
    var that=this;
    var price = parseFloat(e.currentTarget.dataset.price);
    var id = parseInt(e.currentTarget.dataset.id);
    var num = parseInt(e.currentTarget.dataset.num);
    var checked = e.currentTarget.dataset.checked;
    var _total = parseFloat(this.data.info.total);
    var _num = parseInt(this.data.info.num);
    var selectAll=0;
    if (checked == 0) {
      _num +=num;
      _total = parseInt(Number(_total).add(Number(price).mul(num)) * 100) / 100;
    } else {
      _num -= num;
      _total = parseInt(Number(_total).subduct(Number(price).mul(num)) * 100) / 100;
    }
    var obj = [];
    var result = this.data.cartList;
    for (var k in result) {
      if (result[k].id == id) {
        if (checked == 0) {
          result[k].checked = 1;
        } else {
          result[k].checked = 0;
        }
      }
      obj.push(result[k]);

    }
    if(_total==0){
      selectAll=0;
    }else{
      selectAll=1;
    }
    this.setData({
      cartList: obj,
      info: { num: _num, total:_total },
      selectAll: selectAll
    });

  },

  /**
   * 勾选全部
   */
  onSelectAll: function (e) {
    var checked = this.data.selectAll;
    var obj = [];
    var result = this.data.cartList;
    var _num = 0;
    var _total = 0;
    if (checked == 0) {
      for (var k in result) {
        result[k].checked = 1;
        _num += parseInt(result[k].goods_num);
        _total = parseInt(Number(_total).add(Number(parseFloat(result[k].sell_money)).mul(parseInt(result[k].goods_num))) * 100) / 100;
        obj.push(result[k]);
      }

      
      checked = 1;
    } else {
      for (var k in result) {
        result[k].checked = 0;
        obj.push(result[k]);
      }
      checked = 0;
    }
    this.setData({
      cartList: obj,
      info: { num: _num, total: _total  },
      selectAll: checked
    });
  },

  /**
   * 去订单页
   */
  goOrder: function () {
    if (this.data.info.num == 0) {
      return false;
    }
    var data = this.data.cartList;
    var obj = [];
    for (var k in data) {
      if (data[k].checked == 1) {
        obj.push(data[k]);
      }
    }
    wx.setStorageSync('cart_info', obj);
    wx.navigateTo({
      url: "../order/order?type=cart",
    })
  },

  // 去产品详情页
  goGoods:function(e){
    var gid = parseInt(e.currentTarget.dataset.gid);
    wx.navigateTo({
      url: '../goods_detail/goods_detail?id='+gid,
    })
  },


  p: {
    currentIndex: -1,
    eventOk: true,
    eventStartOk: true,
    aniOk: true,
    len: 0,//当前位置
    ani: wx.createAnimation(),
    max: 80,
    size: 40
  },
  moveTo: function (index, x) {
    this.p.eventOk = false;//停止事件
    if (x == 0) {
      this.p.currentIndex = -1;
      if (this.p.len > 0 - this.p.max / 2) {
        if (this.p.len > 0) {
          this.p.ani.translateX(this.p.size).step({
            duration: 100,
            timingFunction: 'ease-out'
          });

        }
        this.p.ani.translateX(0 - this.p.size).step({
          duration: 200,
          timingFunction: 'ease'
        });
      }
    }
    if (x == 0 - this.p.max) {
      this.p.currentIndex = index;
      this.p.ani.translateX(x - this.p.size).step({
        duration: 200,
        timingFunction: 'ease'
      });
    }
    this.p.ani.translateX(x).step({
      duration: 200,
      timingFunction: 'ease-out'
    });
    var obj = {};
    var key = "cartList[" + index + "].ani";
    obj[key] = this.p.ani.export();
    // console.log(obj)
    this.setData(obj);
  },
  ptouchsatrt: function (e) {

    var index = e.currentTarget.dataset.index;
    console.log(index)
    if (this.p.currentIndex >= 0) {
      this.moveTo(this.p.currentIndex, 0);
      return;
    }
    if (this.p.eventStartOk) {
      this.p.eventOk = true;
      this.p.len = 0;
      var pt = e.changedTouches[0];
      pt.aaaaaaa = 11111;
      this.p.x = pt.pageX;
      this.p.y = pt.pageY;
    }
  },
  ptouchend: function (e) {
    if (this.p.eventOk) {
      var pt = e.changedTouches[0];
      var len = pt.pageX - this.p.x;//预计目标位置
      var ht = pt.pageY - this.p.y;
      if (len != 0 && Math.abs(ht) / Math.abs(len) < 0.3) {//滑动倾斜度限制
        this.p.len = len;
        var index = e.currentTarget.dataset.index;
        if (len > 0 - this.p.max / 2) {
          this.moveTo(index, 0);
        } else {
          this.moveTo(index, 0 - this.p.max);
        }
      }
    }
    this.p.eventOk = false;
    this.p.eventStartOk = false;
    var _this = this;
    if (this.p.tm) {
      clearTimeout(this.p.tm);
    }
    this.p.tm = setTimeout(function () {
      _this.p.eventStartOk = true;
    }, 300);
  },

  /**
   * 删除
   */
  del: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var price = e.currentTarget.dataset.price;
    var num = e.currentTarget.dataset.num;
    var id = that.data.cartList[index].id;
    var _total = that.data.info.total;
    var _num = that.data.info.num;
    var checked = e.currentTarget.dataset.checked;
    base.user.user_id = wx.getStorageSync('user_id');
    wx.request({
      url: base.path.api + 'ShopCart.RemoveCart',
      data: { 
        cartid: id,
        md5key: base.user.session_key ,
        aid: base.user.aid,
        uid: base.user.user_id
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        base.sessionId(base);
        var result = response.data;
        console.log(result)
        if (result.ret == 200) {
          var obj = [];
          for (var k in that.data.cartList) {
            if (k == index) {
              continue;
            }
            obj.push(that.data.cartList[k]);
          }
          if (checked==1){
            _total -= price;
            _num -= num;
          }
          that.moveTo(index, 0);
          that.setData({
            cartList: obj,
            info: { num: _num, total: parseInt(_total * 100) / 100  }
          });
        }else {
          wx.showModal({
            showCancel: false,
            title: '',
            content: result.msg
          });
        }
      }
    });
  }
});